﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using fbasync.webcomponents;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace fbasync.web
{
    public partial class TemplateManager : FacebookPage
    {
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            var uiTopRepeat = uiViews.FindControl("uiTopRepeat") as Repeater;
            uiTopRepeat.ItemDataBound += new RepeaterItemEventHandler(uiTopRepeat_ItemDataBound);
            uiTopRepeat.ItemCommand += new RepeaterCommandEventHandler(uiTopRepeat_ItemCommand);
            uiAdd.Click += new EventHandler(uiAdd_Click);

            var uiEditForm = uiViews.FindControl("uiEditForm") as FormView;
            uiEditForm.ItemCommand += new FormViewCommandEventHandler(uiEditForm_ItemCommand);
            if (!Page.IsPostBack)
            {
                uiApiKey.Text = Connection.ApplicationKey;
                uiSecret.Text = Connection.Secret;
                LoadTemplates();
            }
        }

        void uiEditForm_ItemCommand(object sender, FormViewCommandEventArgs e)
        {
            if (e.CommandName == "save")
            {
                var id = long.Parse((string)e.CommandArgument);
                if (id == 0) //adding
                {
                    var stories = new List<StoryTemplate>();
                    var uiEditForm = uiViews.FindControl("uiEditForm") as FormView;
                    var uiOneLiners = uiEditForm.FindControl("uiOneLiners") as TextBox;
                    List<StoryTemplate> oneLines = new List<StoryTemplate>();
                    using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(uiOneLiners.Text)))
                    {
                        using (var sr = new StreamReader(ms))
                        {
                            while (!sr.EndOfStream)
                            {
                                var line = sr.ReadLine();
                                oneLines.Add(new StoryTemplate { template_title = line });
                            }
                        }
                    }

                    var uiFullStoryTitle = uiEditForm.FindControl("uiFullStoryTitle") as TextBox;
                    var uiFullStoryBody = uiEditForm.FindControl("uiFullStoryBody") as TextBox;

                    StoryTemplate fullStory;
                    if (!string.IsNullOrEmpty(uiFullStoryTitle.Text) && !string.IsNullOrEmpty(uiFullStoryBody.Text))
                        fullStory = new StoryTemplate { template_title = uiFullStoryTitle.Text, template_body = uiFullStoryBody.Text };
                    else fullStory = null;

                    Connection.RegisterTemplateBundleCompleted +=
                        delegate
                        {
                            uiViews.ActiveViewIndex = 0;
                            LoadTemplates();
                        };
                    Connection.RegisterTemplateBundleAsync(new StoryTemplateBundle { OneLineStories = oneLines, FullStory = fullStory }, null);
                }
                else //updating. delete old. add new.
                {
                    uiViews.ActiveViewIndex = 0;
                    LoadTemplates();
                }
            }
            else if (e.CommandName == "cancel")
            {
                uiViews.ActiveViewIndex = 0;
                LoadTemplates();
            }
        }

        void uiAdd_Click(object sender, EventArgs e)
        {
            var uiEditForm = uiViews.FindControl("uiEditForm") as FormView;
            uiEditForm.DataSource = new StoryTemplateBundle[] { new StoryTemplateBundle { Created = DateTime.Now, FullStory = new StoryTemplate(), ID = 0, OneLineStories = new List<StoryTemplate>(), ShortStories = new List<StoryTemplate>() } };
            uiViews.ActiveViewIndex = 1;
            LoadTemplates();
        }

        private void LoadTemplates()
        {
            Connection.GetRegisteredTemplateBundlesCompleted +=
                (sender, e) =>
                {
                    var uiTopRepeat = uiViews.FindControl("uiTopRepeat") as Repeater;
                    uiTopRepeat.DataSource = e.Result;
                    DataBind();
                };

            Connection.GetRegisteredTemplateBundlesAsync(null);
        }

        void uiTopRepeat_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (null == e.CommandArgument) return;

            var id = long.Parse((string)e.CommandArgument);
            if (e.CommandName == "edit")
            {
                //change out the form
                Connection.GetRegisteredTemplateBundleCompleted +=
                    (sender, e2) =>
                    {
                        var uiEditForm = uiViews.FindControl("uiEditForm") as FormView;
                        uiEditForm.DataSource = new StoryTemplateBundle[] { e2.Result };
                        DataBind();
                    };
                Connection.GetRegisteredTemplateBundleAsync(null);
                uiViews.ActiveViewIndex = 1;
            }
            else if (e.CommandName == "delete")
            {
                uiViews.ActiveViewIndex = 0;
                Connection.DeactivateTemplateBundleCompleted += delegate { LoadTemplates(); };
                Connection.DeactivateTemplateBundleAsync(id, null);
            }
        }

        void uiTopRepeat_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            var uiOneLineRepeat = e.Item.FindControl("uiOneLineRepeat") as Repeater;
            var uiShortRepeat = e.Item.FindControl("uiShortRepeat") as Repeater;
            var bundle = e.Item.DataItem as StoryTemplateBundle;

            uiOneLineRepeat.DataSource = bundle.OneLineStories;
            uiOneLineRepeat.DataBind();
            uiShortRepeat.DataSource = bundle.ShortStories;
            uiShortRepeat.DataBind();
        }

        protected StoryTemplateBundle EditingBundle { get { return ViewState["editingtemplate"] as StoryTemplateBundle; } set { ViewState["editingtemplate"] = value; } }
    }
}
